/*
 ============================================================================
 Name        : util.c
 Author      : Ana Roig & Pablo Abad
 Version     : 1.0
 Description : Utilidades varias compartidas
 ============================================================================
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include "util.h"
#include "genpasswd.h"

#define ASCII_MIN 32
#define ASCII_MAX 127

void
calculateHash(unsigned char result[SHA_DIGEST_LENGTH], char *message) {
    SHA_CTX c;
    SHA1_Init(&c);
    SHA1_Update(&c, message, strlen(message));
    SHA1_Final(result, &c);
}	

/*
 * Convierte de un buffer de bytes a un string con la representacion
 * hexadecimal. dest debe tener al menos 2*size+1 bytes de longitud
 */
void
byte2hex(char *dest, unsigned char *source, int size) {
	char *current = dest;
	while(size-- > 0) {
		sprintf(current, "%02x", *source++);
		current += 2;
	}
}

void
hex2byte(unsigned char *dest, char *source, int size) {
	while(size-- > 0) {
		unsigned int num;
		sscanf(source, "%2X", &num);
		*dest++ = (unsigned char)num;
		source += 2;
	}
}

FILE*
safefopen(const char *name, char *mode) {
	FILE *file;
	if ((file = fopen(name , mode)) == NULL) {
		printf("No se pudo abrir el archivo %s: %s\n", name, strerror(errno));
		exit(1);
	}
	return file;
}

int
readfile(const char *filePath, char ** dest, int maxSize) {
    FILE * inf = NULL;
    int readSize = 0;
	char * buf;
    inf = safefopen(filePath, "rb");
	buf = *dest;
	buf = malloc(sizeof(char) * maxSize);
	
    if (inf != NULL)
    {
        readSize = fread(buf, 1, maxSize, inf) ;
        fclose(inf);
    }
	
	*dest = buf;
    return readSize;
}

int
checkASCII(char *str, int len)
{
    int i;
	
    if (str == NULL)
		return 0;
	
    for (i=0 ; i<16 ; i++)
    {
        if (str[i] < ASCII_MIN || (unsigned char)str[i] > ASCII_MAX)
            return 0;
    }
	
    return 1;
}
